<template>
	<view class="pb-150">
		<!-- 导航栏 -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar title="经济林种植产量管理" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

		<!-- 顶部筛选 -->
		<view class="search-filter-box">
			<view class="filter-row">
				<text class="filter-label w-105">搜索</text>
				<u--input v-model="query.search" placeholder="请输入上报人/产量"
					:customStyle="{ height: '64rpx', fontSize: '16rpx', padding: '0 16rpx' }"></u--input>
			</view>
			<view class="filter-row">
				<text class="filter-label">上报时间</text>
				<view class="date-inputs">
					<view class="date-input-wrapper" @click="showStartPicker = true">
						<u--input v-model="query.start" placeholder="开始日期" readonly
							:customStyle="{ height: '64rpx', fontSize: '16rpx', padding: '0 16rpx' }"></u--input>
						<u-icon name="calendar" size="16" color="#999" class="calendar-icon" />
					</view>
					<text class="date-separator">至</text>
					<view class="date-input-wrapper end" @click="showEndPicker = true">
						<u--input v-model="query.end" placeholder="结束日期" readonly
							:customStyle="{ height: '64rpx', fontSize: '16rpx', padding: '0 16rpx' }"></u--input>
						<u-icon name="calendar" size="16" color="#999" class="calendar-icon" />
					</view>
				</view>
			</view>
			<view class="filter-row">
				<view class="filter-item">
					<text class="filter-label">行政区划</text>
					<view class="picker-input" @click="openRegionPicker">
						<text>{{ query.area || '全部' }}</text>
						<u-icon name="arrow-down" size="12" color="#999" />
					</view>
				</view>
				<view class="filter-item">
					<text class="filter-label">树种</text>
					<view class="picker-input" @click="showSpeciesPicker = true">
						<text>{{ query.species || '全部' }}</text>
						<u-icon name="arrow-down" size="12" color="#999" />
					</view>
				</view>
				<view class="filter-item">
					<text class="filter-label">年度</text>
					<view class="picker-input">
						<picker mode="date" fields="year" :value="yearValue" @change="onYearChange">
							<view style="width:100%;display:flex;align-items:center;justify-content:space-between;">
								<text>{{ query.year || '全部' }}</text>
								<u-icon name="arrow-down" size="12" color="#999" />
							</view>
						</picker>
					</view>
				</view>
			</view>
			<view class="action-buttons">
				<u-button type="primary" size="small" @click="onSearch"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }">查询</u-button>
				<u-button size="small" @click="onReset"
					:customStyle="{ background: '#fff', borderColor: '#0A993B', color: '#0A993B' }">重置</u-button>
			</view>
		</view>

		<!-- 列表 -->
		<view class="list-wrap">
			<view class="card" v-for="(item, index) in filteredList" :key="index">
				<view class="card-hd">
					<view class="title">{{ item.year }}　{{ item.name }}</view>
				</view>
				<view class="card-bd">
					<view class="row2">行政区划：{{ item.area }}</view>
					<view class="row2">种植产量（吨）：{{ item.yieldTon }}</view>
					<view class="row2">状态：{{ item.postFlag == 0 ? '草稿' : '已发布' }}</view>
					<view class="row2">审核状态：{{ item.auditStatus == 0 ? '待审核' : '已审核' }}
					</view>
					<view class="row2 time">上报人：{{ item.reporter }}　上报时间：{{ item.time }}</view>
				</view>
				<u-button size="small" @click="onView(item)"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }">查看</u-button>
				<u-button size="small" @click="onEdit(item)" class="mt-20" v-if="item.postFlag == 0"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }">编辑</u-button>
				<u-button size="small" @click="onDelete(item)" class="mt-20" v-if="item.postFlag == 0"
					:customStyle="{ background: '#ff0000', borderColor: '#ff0000', color: '#fff' }">删除</u-button>
			</view>
			<view v-if="filteredList.length === 0" class="empty">
				<u-empty mode="data" icon="data"></u-empty>
			</view>
		</view>

		<!-- 详情弹框 -->
		<u-popup :show="showDetail" mode="center" :round="18" :customStyle="{ width: '670rpx' }"
			@close="showDetail = false">
			<view class="detail-modal">
				<view class="detail-header">
					<text class="detail-title">经济林种植产量详情</text>
					<u-icon name="close" size="28" color="#999" @click="showDetail = false"></u-icon>
				</view>
				<view class="detail-body">
					<view class="d-row"><text class="d-label">行政区划：</text><text class="d-value">{{ currentItem.area
							}}</text></view>
					<view class="d-row"><text class="d-label">树种：</text><text class="d-value">{{ currentItem.name
							}}</text></view>
					<view class="d-row"><text class="d-label">种植产量（吨）：</text><text class="d-value">{{
							currentItem.yieldTon }}</text></view>
					<view class="d-row"><text class="d-label">上报人：</text><text class="d-value">{{ currentItem.reporter
							}}</text></view>
					<view class="d-row"><text class="d-label">上报时间：</text><text class="d-value">{{ currentItem.time
							}}</text></view>
					<view class="d-row"><text class="d-label">年度：</text><text class="d-value">{{ currentItem.year
							}}</text></view>
				</view>
				<view class="detail-actions">
					<u-button @click="showDetail = false">关闭</u-button>
				</view>
			</view>
		</u-popup>
		<!-- 编辑弹框 -->
		<u-popup :show="showEdit" mode="center" :round="18" :customStyle="{ width: '670rpx' }"
			@close="showEdit = false">
			<view class="detail-modal">
				<view class="detail-header">
					<text class="detail-title">修改经济林种植产量</text>
					<u-icon name="close" size="28" color="#999" @click="showEdit = false"></u-icon>
				</view>
				<view class="detail-body">
					<view class="filter-item">
						<text class="filter-label">行政区划</text>
						<view class="picker-input" @click="openEditRegionPicker">
							<text>{{ editForm.area || '请选择' }}</text>
							<u-icon name="arrow-down" size="12" color="#999" />
						</view>
					</view>
					<view class="filter-item">
						<text class="filter-label">树种</text>
						<view class="picker-input" @click="showEditSpeciesPicker = true">
							<text>{{ editForm.speciesName || '请选择' }}</text>
							<u-icon name="arrow-down" size="12" color="#999" />
						</view>
					</view>
					<view class="filter-item">
						<text class="filter-label">年度</text>
						<view class="picker-input">
							<picker mode="date" fields="year" :value="editYearValue" @change="onEditYearChange">
								<view style="width:100%;display:flex;align-items:center;justify-content:space-between;">
									<text>{{ editForm.year || '请选择' }}</text>
									<u-icon name="arrow-down" size="12" color="#999" />
								</view>
							</picker>
						</view>
					</view>
					<view class="d-row">
						<text class="d-label">种植产量（吨）：</text>
						<u-number-box v-model="editForm.yieldTon" @change="valChange"></u-number-box>
					</view>
				</view>
				<view class="detail-actions rowsa w-700">
					<view class="w-100 h-50 border br-8 bg colfff rowsc rowsm" @click="showEdit = false">关闭</view>
					<view class="w-100 h-50 border br-8 bg colfff rowsc rowsm" @click="onSave">存草稿</view>
					<view class="w-100 h-50 border br-8 bg colfff rowsc rowsm" @click="onPublish">提交</view>
				</view>
			</view>
		</u-popup>

		<!-- 选择器 -->
		<u-datetime-picker :show="showStartPicker" v-model="startTimestamp" mode="date" @confirm="onStartConfirm"
			@cancel="showStartPicker = false" @close="showStartPicker = false" />
		<u-datetime-picker :show="showEndPicker" v-model="endTimestamp" mode="date" @confirm="onEndConfirm"
			@cancel="showEndPicker = false" @close="showEndPicker = false" />
		<u-picker :show="showAreaPicker" :columns="[areaOptions]" @confirm="onAreaConfirm"
			@cancel="showAreaPicker = false" @close="showAreaPicker = false" />
		<u-picker :show="showSpeciesPicker" :columns="[speciesOptions]" @confirm="onSpeciesConfirm"
			@cancel="showSpeciesPicker = false" @close="showSpeciesPicker = false" />
		<u-picker :show="showEditSpeciesPicker" :columns="[speciesOptions]" @confirm="onEditSpeciesConfirm"
			@cancel="showEditSpeciesPicker = false" @close="showEditSpeciesPicker = false" />
		<!-- 年度改为原生year选择器，移除u-picker -->
		<!-- 行政区划三级选择器 -->
		<u-picker :show="regionPickerShow" :columns="regionColumns" @confirm="onRegionConfirm"
			@cancel="regionPickerShow = false" @change="onRegionPickerChange" @close="regionPickerShow = false" />
		<u-safe-bottom></u-safe-bottom>
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import { getEconomicForestYield, getTreeSpeciesList, getDeptList, editEconomicForestYield, deleteEconomicForestYield } from '@/api/economicforest'
export default {
	mixins: [navbarMixin],
	data() {
		return {
			query: { start: '', end: '', area: '', species: '', year: '', search: '' },
			showStartPicker: false, showEndPicker: false, showAreaPicker: false, showSpeciesPicker: false,
			startTimestamp: Date.now(), // 开始日期时间戳
			endTimestamp: Date.now(), // 结束日期时间戳
			areaOptions: ['全部'],
			speciesOptions: ['全部'],
			list: [],
			showDetail: false,
			showEdit: false,
			currentItem: {},
			editForm: {
				area: '',
				speciesName: '',
				year: '',
				yieldTon: 0,
				treeSpeciesId: '',
				deptId: ''
			},
			showEditSpeciesPicker: false,
			loading: false,
			pageNum: 1,
			pageSize: 10,
			total: 0,
			finished: false,
			// API参数
			apiParams: {
				pageNum: '1',
				pageSize: '10',
				deptId: '',
				treeSpeciesId: ''
			},
			// 行政区划树形数据
			regionData: [],
			// 行政区划三级选择器状态
			regionPickerShow: false,
			regionColumns: [[], [], []],
			pIndex: 0,
			cIndex: 0,
			userSelectedLevel: 1, // 记录用户实际选择的层级
			// ID映射
			deptIdMap: {},
			speciesIdMap: {}
		}
	},
	computed: {
		filteredList() {
			return this.list
		},
		yearValue() {
			const y = this.query.year || new Date().getFullYear().toString()
			return `${y}-01-01`
		},
		currentYear() {
			return new Date().getFullYear().toString()
		},
		editYearValue() {
			const y = this.editForm.year || new Date().getFullYear().toString()
			return `${y}-01-01`
		},
	},
	onLoad() {
		this.getList()
		this.getTreeSpeciesList()
		this.getDeptList()
	},
	onReachBottom() {
		if (this.finished || this.loading) return
		this.pageNum += 1
		this.getList(true)
	},
	methods: {
		// 获取列表数据（支持加载更多）
		getList(isLoadMore = false) {
			if (this.loading) return
			this.loading = true
			const params = {
				pageNum: String(this.pageNum),
				pageSize: String(this.pageSize)
			}
			if (this.apiParams.deptId) {
				params.deptId = this.apiParams.deptId
			}
			if (this.apiParams.treeSpeciesId) {
				params.treeSpeciesId = this.apiParams.treeSpeciesId
			}
			// 使用 beginTime 和 endTime 参数
			if (this.query.start) {
				params.beginTime = this.query.start
			}
			if (this.query.end) {
				params.endTime = this.query.end
			}
			if (this.query.year && this.query.year !== '全部') {
				params.year = this.query.year
			}
			if (this.query.search) {
				params.query = this.query.search
			}
			getEconomicForestYield(params).then(res => {
				const rows = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res?.data?.rows) ? res.data.rows : [])
				const total = typeof res?.total === 'number' ? res.total : (typeof res?.data?.total === 'number' ? res.data.total : 0)
				this.total = total
				const mapped = rows.map(item => ({
					id: item.id,
					year: item.year || '—',
					name: item.treeSpeciesName || '—',
					area: this.getDeptNameById(item.deptId) || item.compartment || '—',
					yieldTon: item.output || '—',
					postFlag: item.postFlag,
					auditStatus: item.auditStatus,
					reporter: item.createBy || '—',
					time: item.createTime || '—',
					treeSpeciesId: item.treeSpeciesId,
					deptId: item.deptId
				}))
				this.list = isLoadMore ? this.list.concat(mapped) : mapped
				this.finished = (!mapped.length) || (this.total && this.list.length >= this.total) || (mapped.length < this.pageSize)
			}).catch(err => {
				console.error('获取列表失败:', err)
			}).finally(() => {
				this.loading = false
			})
		},
		// 获取树种列表
		getTreeSpeciesList() {
			getTreeSpeciesList().then(res => {
				if (res && res.length > 0) {
					this.speciesOptions = ['全部', ...res.map(item => item.label)]
					this.speciesIdMap = {}
					res.forEach(item => {
						this.speciesIdMap[item.label] = item.value
					})
				}
			}).catch(err => {
				console.error('获取树种列表失败:', err)
			})
		},
		// 获取行政区划列表
		getDeptList() {
			getDeptList().then(res => {
				if (res && res.data && res.data.length > 0) {
					this.buildRegionTree(res.data)
				}
			}).catch(err => {
				console.error('获取行政区划列表失败:', err)
			})
		},
		// 构建行政区划树形结构
		buildRegionTree(deptList) {
			const topLevel = deptList.filter(item => item.parentId === 0)
			const buildTree = (parentId) => {
				return deptList
					.filter(item => item.parentId === parentId)
					.map(item => ({
						label: item.deptName,
						value: item.deptId,
						children: buildTree(item.deptId)
					}))
			}
			this.regionData = topLevel.map(item => ({
				label: item.deptName,
				value: item.deptId,
				children: buildTree(item.deptId)
			}))
			this.generateAreaOptions()
		},
		// ——— 行政区划懒加载 ———
		async fetchProvinces() {
			try {
				await new Promise(resolve => {
					uni.request({
						url: '/dev-api/system/region/provinces',
						method: 'GET',
						success: (res) => {
							if (res && res.statusCode === 200 && Array.isArray(res.data)) {
								this.regionData = (res.data || []).map(p => ({ label: p.name || p.label, value: p.code || p.value, children: [] }))
							}
							resolve()
						},
						fail: () => resolve()
					})
				})
				if (this.regionData.length) return
			} catch (_) { }
			const provinces = [
				'北京市','天津市','上海市','重庆市',
				'河北省','山西省','辽宁省','吉林省','黑龙江省',
				'江苏省','浙江省','安徽省','福建省','江西省','山东省','河南省','湖北省','湖南省',
				'广东省','海南省','四川省','贵州省','云南省',
				'陕西省','甘肃省','青海省',
				'台湾省','内蒙古自治区','广西壮族自治区','西藏自治区','宁夏回族自治区','新疆维吾尔自治区',
				'香港特别行政区','澳门特别行政区'
			]
			this.regionData = provinces.map(n => ({ label: n, value: n, children: [] }))
		},
		async ensureCitiesFor(pIdx) {
			const prov = this.regionData[pIdx]
			if (!prov) return
			if (prov.children && prov.children.length) {
				this.regionColumns.splice(1, 1, ['请选择', ...prov.children.map(c => c.label)])
				return
			}
			this.loadingCities = true
			let cities = []
			try {
				await new Promise(resolve => {
					uni.request({
						url: '/dev-api/system/region/cities',
						method: 'GET',
						data: { province: prov.value },
						success: (res) => {
							if (res && res.statusCode === 200 && Array.isArray(res.data)) {
								cities = (res.data || []).map(c => ({ label: c.name || c.label, value: c.code || c.value, children: [] }))
							}
							resolve()
						},
						fail: () => resolve()
					})
				})
			} catch (_) { }
			if (!cities.length) {
				switch (prov.label) {
					case '北京市':
						cities = [{ label: '北京市', value: '110100', children: [] }]
						break
					case '上海市':
						cities = [{ label: '上海市', value: '310100', children: [] }]
						break
					case '广东省':
						cities = [
							{ label: '广州市', value: '440100', children: [] },
							{ label: '深圳市', value: '440300', children: [] },
							{ label: '佛山市', value: '440600', children: [] }
						]
						break
					case '山东省':
						cities = [
							{ label: '济南市', value: '370100', children: [] },
							{ label: '青岛市', value: '370200', children: [] }
						]
						break
					default:
						cities = []
				}
			}
			this.$set(this.regionData[pIdx], 'children', cities)
			this.regionColumns.splice(1, 1, cities.length ? ['请选择', ...cities.map(c => c.label)] : ['请选择'])
			this.loadingCities = false
		},
		async ensureDistsFor(pIdx, cIdx) {
			const prov = this.regionData[pIdx]
			const city = prov?.children?.[cIdx]
			if (!city) {
				this.regionColumns.splice(2, 1, ['请选择'])
				return
			}
			if (city.children && city.children.length) {
				this.regionColumns.splice(2, 1, ['请选择', ...city.children.map(d => d.label)])
				return
			}
			this.loadingDists = true
			let dists = []
			try {
				await new Promise(resolve => {
					uni.request({
						url: '/dev-api/system/region/districts',
						method: 'GET',
						data: { city: city.value },
						success: (res) => {
							if (res && res.statusCode === 200 && Array.isArray(res.data)) {
								dists = (res.data || []).map(d => ({ label: d.name || d.label, value: d.code || d.value }))
							}
							resolve()
						},
						fail: () => resolve()
					})
				})
			} catch (_) { }
			if (!dists.length) {
				switch (city.label) {
					case '北京市':
						dists = [
							{ label: '东城区', value: '110101' },
							{ label: '西城区', value: '110102' },
							{ label: '朝阳区', value: '110105' },
							{ label: '海淀区', value: '110108' },
							{ label: '丰台区', value: '110106' }
						]
						break
					case '上海市':
						dists = [
							{ label: '黄浦区', value: '310101' },
							{ label: '徐汇区', value: '310104' },
							{ label: '长宁区', value: '310105' },
							{ label: '静安区', value: '310106' },
							{ label: '浦东新区', value: '310115' }
						]
						break
					case '广州市':
						dists = [
							{ label: '越秀区', value: '440104' },
							{ label: '天河区', value: '440106' },
							{ label: '白云区', value: '440111' }
						]
						break
					case '济南市':
						dists = [
							{ label: '历下区', value: '370102' },
							{ label: '市中区', value: '370103' }
						]
						break
					case '青岛市':
						dists = [
							{ label: '市南区', value: '370202' },
							{ label: '崂山区', value: '370212' }
						]
						break
					default:
						dists = []
				}
			}
			this.$set(city, 'children', dists)
			this.regionColumns.splice(2, 1, dists.length ? ['请选择', ...dists.map(d => d.label)] : ['请选择'])
			this.loadingDists = false
		},
		// 生成扁平化的行政区划选项
		generateAreaOptions() {
			const options = ['全部']
			const traverse = (nodes, path = '') => {
				nodes.forEach(node => {
					const currentPath = path ? `${path}/${node.label}` : node.label
					options.push(currentPath)
					if (!this.deptIdMap) this.deptIdMap = {}
					this.deptIdMap[currentPath] = node.value
					if (node.children && node.children.length > 0) {
						traverse(node.children, currentPath)
					}
				})
			}
			traverse(this.regionData)
			this.areaOptions = options
		},
		// 根据部门ID获取部门名称
		getDeptNameById(deptId) {
			if (this.regionData && deptId) {
				return this.findDeptPathById(deptId) || deptId
			}
			return deptId
		},
		findDeptPathById(deptId) {
			const findPath = (nodes, targetId, path = '') => {
				for (let node of nodes) {
					const currentPath = path ? `${path}/${node.label}` : node.label
					if (node.value == deptId) {
						return currentPath
					}
					if (node.children && node.children.length > 0) {
						const result = findPath(node.children, targetId, currentPath)
						if (result) return result
					}
				}
				return null
			}
			return findPath(this.regionData, deptId)
		},
		// —— 行政区划（三级） ——
		openRegionPicker() {
			// 重置用户选择层级
			this.userSelectedLevel = 1
			// 首次打开先加载省份
			if (!this.regionData.length) {
				this.fetchProvinces().then(() => {
					this.initRegionColumns()
					// 不预加载城市和区县，让用户可以选择省份后直接确认
				})
			} else if (!this.regionColumns[0].length) {
				this.initRegionColumns()
			}
			this.regionPickerShow = true
		},
		initRegionColumns() {
			const provs = this.regionData.map(p => p.label)
			// 初始状态所有列都加"请选择"，让用户可以滚动
			this.regionColumns = [
				['请选择', ...provs],
				['请选择'],
				['请选择']
			]
		},
		onRegionPickerChange(e) {
			const col = e?.columnIndex ?? e?.detail?.column
			const idx = e?.index ?? e?.detail?.value
			if (col === 0) {
				// 第一列有"请选择"，所以索引需要减1
				this.pIndex = Math.max(0, (idx || 1) - 1)
				this.cIndex = 0
				this.userSelectedLevel = 1 // 用户选择了第一列
				// 占位，随后刷新
				this.regionColumns.splice(1, 2, ['加载中...'], ['请选择'])
				this.ensureCitiesFor(this.pIndex).then(() => this.ensureDistsFor(this.pIndex, 0))
			} else if (col === 1) {
				// 第二列有"请选择"，所以索引需要减1
				this.cIndex = Math.max(0, (idx || 1) - 1)
				this.userSelectedLevel = 2 // 用户选择了第二列
				this.regionColumns.splice(2, 1, ['加载中...'])
				this.ensureDistsFor(this.pIndex, this.cIndex)
			} else if (col === 2) {
				this.userSelectedLevel = 3 // 用户选择了第三列
			}
		},
		onRegionConfirm(e) {
			let vals = e?.value || []
			if (!Array.isArray(vals)) vals = [String(vals)]
			const clean = vals.filter(v => v && v !== '请选择')
			this.query.area = clean.join('/') || '全部'
			const prov = this.regionData[this.pIndex]
			const city = prov?.children?.[this.cIndex]
			let dist
			if (clean[2] && city?.children?.length) {
				dist = city.children.find(d => d.label === clean[2])
			}
			// 只传最后一级 deptId（如无下级则取当前级）
			this.selectedDeptId = dist?.value || city?.value || prov?.value || ''
			this.regionPickerShow = false
		},
		onSearch() {
			this.apiParams.pageNum = '1'
			this.pageNum = 1
			this.finished = false
			this.list = []
			this.getList()
		},
		onReset() {
			this.query = { start: '', end: '', area: '', species: '', year: '', search: '' }
			this.apiParams = {
				pageNum: '1',
				pageSize: '10',
				deptId: '',
				treeSpeciesId: ''
			}
			this.pageNum = 1
			this.finished = false
			this.list = []
			this.getList()
		},
		// 日期选择器确认
		onStartConfirm(e){ 
			// u-datetime-picker 返回的是时间戳，需要转换为 YYYY-MM-DD 格式
			const timestamp = e?.value || e?.detail?.value || this.startTimestamp
			if (timestamp) {
				this.startTimestamp = timestamp // 同步更新时间戳
				const date = new Date(timestamp)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				this.query.start = `${year}-${month}-${day}`
			}
			this.showStartPicker = false 
		},
		onEndConfirm(e){ 
			// u-datetime-picker 返回的是时间戳，需要转换为 YYYY-MM-DD 格式
			const timestamp = e?.value || e?.detail?.value || this.endTimestamp
			if (timestamp) {
				this.endTimestamp = timestamp // 同步更新时间戳
				const date = new Date(timestamp)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				this.query.end = `${year}-${month}-${day}`
			}
			this.showEndPicker = false 
		},
		onAreaConfirm(e) {
			const selectedArea = e.value[0]
			this.query.area = selectedArea
			if (selectedArea !== '全部' && this.deptIdMap && this.deptIdMap[selectedArea]) {
				this.apiParams.deptId = this.deptIdMap[selectedArea]
			} else {
				this.apiParams.deptId = ''
			}
			this.showAreaPicker = false
		},
		onSpeciesConfirm(e) {
			const selectedSpecies = e.value[0]
			this.query.species = selectedSpecies
			if (selectedSpecies !== '全部' && this.speciesIdMap && this.speciesIdMap[selectedSpecies]) {
				this.apiParams.treeSpeciesId = this.speciesIdMap[selectedSpecies]
			} else {
				this.apiParams.treeSpeciesId = ''
			}
			this.showSpeciesPicker = false
		},
		// 年度选择变更（与01area.vue一致）
		onYearChange(e) {
			const y = String(e?.detail?.value || '').split('-')[0] || ''
			this.query.year = y
			// 同时更新API参数
			this.apiParams.year = y
		},
		onView(item) { this.currentItem = item; this.showDetail = true },
		
		// 编辑相关方法
		onEdit(item) {
			this.currentItem = item
			// 初始化编辑表单
			this.editForm = {
				area: item.area || '',
				speciesName: item.name || '',
				year: item.year || '',
				yieldTon: item.yieldTon || 0,
				treeSpeciesId: item.treeSpeciesId || '',
				deptId: item.deptId || ''
			}
			this.showEdit = true
		},
		
		onDelete(item) {
			this.currentItem = item
			uni.showModal({
				title: '提示',
				content: '确定删除该经济林种植产量吗？',
				success: (res) => {
					if (res.confirm) {
						deleteEconomicForestYield(item.id).then(res => {
							if (res.code == 200) {
								uni.showToast({ title: '删除成功', icon: 'success' })
								this.getList()
							} else {
								uni.showToast({ title: res.message, icon: 'none' })
							}
						})
					}
				}
			})
		},
		
		// 编辑相关方法
		valChange() {
			// 数值变化时的处理
		},
		
		// 保存草稿
		onSave() {
			this.submitEdit(0)
		},
		
		// 提交
		onPublish() {
			this.submitEdit(1)
		},
		
		// 编辑弹框中的行政区划选择器
		openEditRegionPicker() {
			// 重置用户选择层级
			this.userSelectedLevel = 1
			// 首次打开先加载省份
			if (!this.regionColumns[0].length) {
				this.initRegionColumns()
			}
			this.regionPickerShow = true
		},
		
		// 编辑弹框中的树种选择器确认
		onEditSpeciesConfirm(e) {
			const selectedSpecies = e.value[0]
			this.editForm.speciesName = selectedSpecies
			
			// 设置对应的树种ID
			if (selectedSpecies !== '全部' && this.speciesIdMap && this.speciesIdMap[selectedSpecies]) {
				this.editForm.treeSpeciesId = this.speciesIdMap[selectedSpecies]
			} else {
				this.editForm.treeSpeciesId = ''
			}
			
			this.showEditSpeciesPicker = false
		},
		
		// 编辑弹框中的年度选择变更
		onEditYearChange(e) {
			const y = String(e?.detail?.value || '').split('-')[0] || ''
			this.editForm.year = y
		},
		
		// 提交编辑数据
		submitEdit(postFlag) {
			// 校验必要字段
			if (!this.editForm.yieldTon || this.editForm.yieldTon <= 0) {
				uni.showToast({ title: '请输入种植产量', icon: 'none' })
				return
			}
			if (!this.editForm.year) {
				uni.showToast({ title: '请选择年度', icon: 'none' })
				return
			}
			if (!this.editForm.treeSpeciesId) {
				uni.showToast({ title: '请选择树种', icon: 'none' })
				return
			}
			if (!this.editForm.deptId) {
				uni.showToast({ title: '请选择行政区划', icon: 'none' })
				return
			}

			// 获取树种名称
			const treeSpecies = this.editForm.speciesName

			// 构建提交数据，参照01area.vue的传参方式
			const payload = {
				id: this.currentItem.id, // 编辑时需要传递ID
				output: Number(this.editForm.yieldTon),
				year: this.editForm.year,
				postFlag: postFlag,
				treeSpeciesId: this.editForm.treeSpeciesId,
				treeSpecies: treeSpecies,
				compartment: this.editForm.area,
				deptId: this.editForm.deptId
			}

			console.log('编辑提交参数:', payload)

			uni.showLoading({ title: postFlag === 1 ? '提交中...' : '保存中...' })

			editEconomicForestYield(payload).then(res => {
				uni.hideLoading()
				console.log('编辑响应:', res)
				if (res && res.code === 200) {
					uni.showToast({ 
						title: postFlag === 1 ? '提交成功' : '保存成功', 
						icon: 'success' 
					})
					this.showEdit = false
					// 刷新列表
					this.onReset()
				} else {
					uni.showToast({ 
						title: res?.msg || (postFlag === 1 ? '提交失败' : '保存失败'), 
						icon: 'none' 
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('编辑失败:', err)
				uni.showToast({ 
					title: '网络错误，请重试', 
					icon: 'none' 
				})
			})
		},
		onRegionConfirm(e) {
			let vals = e?.value || []
			if (!Array.isArray(vals)) vals = [String(vals)]
			const clean = vals.filter(v => v && v !== '请选择' && v !== '加载中...')

			console.log('过滤后的值:', clean)

			// 反查编码 - 根据用户实际选择的层级来确定
			const regionValue = []
			const regionText = []

			// 第一列：省份 - 只有当用户真正选择了省份时才添加
			if (this.userSelectedLevel >= 1 && clean[0]) {
				const prov = this.regionData.find(p => p.label === clean[0])
				if (prov) {
					regionValue.push(prov.value)
					regionText.push(prov.label)

					// 第二列：城市 - 只有当用户真正选择了第二列时才添加
					if (this.userSelectedLevel >= 2 && clean[1] && prov.children) {
						const city = prov.children.find(c => c.label === clean[1])
						if (city) {
							regionValue.push(city.value)
							regionText.push(city.label)

							// 第三列：区县 - 只有当用户真正选择了第三列时才添加
							if (this.userSelectedLevel >= 3 && clean[2] && city.children) {
								const dist = city.children.find(d => d.label === clean[2])
								if (dist) {
									regionValue.push(dist.value)
									regionText.push(dist.label)
								}
							}
						}
					}
				}
			}

			// 根据当前状态更新对应的数据
			if (this.showEdit) {
				// 编辑弹框中的行政区划选择
				this.editForm.area = regionText.join('/') || ''
				if (regionValue.length > 0) {
					this.editForm.deptId = regionValue[regionValue.length - 1]
				} else {
					this.editForm.deptId = ''
				}
			} else {
				// 筛选条件中的行政区划选择
				this.query.area = regionText.join('/') || '全部'
				if (regionValue.length > 0) {
					this.apiParams.deptId = regionValue[regionValue.length - 1]
				} else {
					this.apiParams.deptId = ''
				}
			}
			
			this.regionPickerShow = false
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 750rpx;
	z-index: 1;
}

.search-filter-box {
	background: #fff;
	margin: 20rpx;
	padding: 20rpx;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.filter-row {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin-bottom: 12rpx;
}

.filter-item {
	display: flex;
	align-items: center;
}

.filter-label {
	color: #666;
	font-size: 26rpx;
}

.date-inputs {
	display: flex;
	align-items: center;
	flex: 1;
	gap: 12rpx;
}

.date-input-wrapper {
	position: relative;
	flex: 1;
}

.date-input-wrapper.end {
	flex: .9;
}

.calendar-icon {
	position: absolute;
	right: 16rpx;
	top: 50%;
	transform: translateY(-50%);
	pointer-events: none;
}

.date-separator {
	color: #999;
	font-size: 26rpx;
}

.picker-input {
	min-width: 120rpx;
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: #f8f9fa;
	padding: 14rpx;
	border-radius: 12rpx;
	color: #333;
	font-size: 26rpx;
}

.action-buttons {
	display: flex;
	gap: 16rpx;
	margin-top: 6rpx;
}

.action-buttons .u-button {
	flex: 1;
}

.list-wrap {
	margin: 20rpx;
}

.card {
	background: #fff;
	border-radius: 16rpx;
	padding: 16rpx;
	margin-bottom: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.card-hd {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
}

.card-bd {
	margin-top: 10rpx;
	color: #666;
}

.row2 {
	font-size: 24rpx;
	margin: 20rpx 0;
}

.time {
	color: #999;
}

.empty {
	padding: 80rpx 0;
}

/* 详情弹框 */
.detail-modal {
	background: #fff;
	border-radius: 18rpx;
	overflow: hidden;
}

.detail-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 28rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.detail-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.detail-body {
	padding: 24rpx 28rpx;
}

.d-row {
	display: flex;
	margin-bottom: 14rpx;
	align-items: baseline;
}

.d-label {
	width: 200rpx;
	color: #666;
	font-size: 26rpx;
}

.d-value {
	flex: 1;
	color: #333;
	font-size: 26rpx;
}

.detail-actions {
	padding: 20rpx 28rpx 28rpx;
	display: flex;
	justify-content: center;
}
</style>
